package com.csc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


import com.csc.domain.User;
import com.csc.service.UserService;

@Controller
public class LoginController {

	static final Logger logger = Logger.getLogger(LoginController.class);
	@Autowired
	UserService USER_SERVICE;

	@RequestMapping(value = "/tologin", method = RequestMethod.GET)
	public String sentoLoginPage(HttpServletRequest request) {
		BasicConfigurator.configure();
		logger.info("send to login page");
		return "login";
	}
	/*@Author Thanh Binh*/
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView checkLoginPage(@RequestParam("userid") String username,
			@RequestParam("password") String password) {
		logger.info("method check login is called " + username);
		String message ="";
		User user = USER_SERVICE.checkLogin(username, password);
		logger.info("print user: " + user);
		ModelAndView modelAndView = new ModelAndView();
		
		if(user!=null){
			modelAndView.addObject("user", username);
			if(user.getIdRole().getIdRole()==1){
				modelAndView.setViewName("searchAccount");
			}else{
				modelAndView.setViewName("adminTransaction");
			}
		}else{
			message = "Wrong username or password";
			modelAndView.addObject("message",message);
			modelAndView.setViewName("login");
		}
		return modelAndView;
		/* HttpSession session = request.getSession(); */
		/*
		 * String message = ""; String username =
		 * request.getParameter("userid"); String password =
		 * request.getParameter("password"); LoginService login = new
		 * LoginService(); User user = login.checkLogin(username, password);
		 * ModelAndView modelAndView = new ModelAndView(); if (null != user) {
		 * 
		 * session.setAttribute("user", user);
		 * 
		 * if (user.getIdRole().getNameRole().equals("Support User")) { return
		 * "searchAccount"; } else { return "redirect:/adminTransaction.html"; }
		 * } else { message = "Wrong username/password or not match";
		 * ModelAndView.addObject("message", message);
		 * 
		 * }
		 * 
		 * logger.info("method check login is ended"); return "login";
		 */

	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logOutMethod(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		session.invalidate();
		return "redirect:/";
	}
}
